package com.lwlk.zdk.controller.Statistics;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.T.*;
import com.lwlk.zdk.util.*;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @ClassName 赵项阳
 * @Description: TODO
 * @Author DELL
 * @Date 2020/6/10
 * @Version V1.0
 **/
@RestController
@Transactional
@RequestMapping(value = "/statistics")
public class StatisticsController {


    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    @Autowired
    TDisEnterpriseMapper tDisEnterpriseMapper;
    @Autowired
    TDisPlatformMapper tDisPlatformMapper;
    @Autowired
    TDisVehicleMapper tDisVehicleMapper;
    @Autowired
    TDisDictionaryMapper disDictionaryMapper;
    @Autowired
    TRegionMapper tRegionMapper;



    @ApiOperation(value = "报警类型展示")
    @RequestMapping(value = "/AlarmType",method = RequestMethod.GET)
    public Response getAlarmType(){
        Response response=new Response();
        List<Map<String, Object>> vehicleAlarmType = disDictionaryMapper.selectVehicleAlarmType();
        response.setData(vehicleAlarmType);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "平台考核统计")
    @RequestMapping(value = "/platformAssmentStatics",method = RequestMethod.GET)
    public JSONObject getPlatformAssmentStatics(String regionCode){
        Map map=new HashMap();
        map.put("regionCode",regionCode);//必选 行政区划码
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/platform/platformAssmentStatics";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }




    @ApiOperation(value = "业户报警统计")
    @RequestMapping(value = "/BusinessAlarmStatistics",method = RequestMethod.GET)
    public JSONObject BusinessAlarmStatistics(String startDate,String endDate,String limit,String page,String eid,String regionCode)  {
        Map map=new HashMap();
        map.put("startDate",startDate);//必传 开始查询时间yyyy-MM-dd
        map.put("endDate",endDate);//必传 结束查询时间yyyy-MM-dd，不要跨年
        map.put("eIds",eid);//企业id,多个id以逗号分隔
        map.put("limit",limit);//必传 页面记录数,默认值为10
        map.put("page",page);//必传 页码，默认值为1
        map.put("regionCode",regionCode);//必传 用户行政区划编码
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/alarmType/enterprise";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer eIds=Integer.parseInt(jsonObject.getString("eId"));//企业ids
            //List<Map<String,Object>>enterprise=sysEnterpriseMapper.selectByeId(eId);//企业名称和所属地区
            List<Map<String,Object>>enterprise=tDisEnterpriseMapper.selectByEidList(eIds);
            if (enterprise.size()==0){
                jsonObject.put("enterpriseName",null);
                jsonObject.put("areaCodeName",null);
                jsonObject.put("industryName",null);
            }else {
                String industry = String.valueOf(enterprise.get(0).get("industry"));
                Integer areaCode = Integer.parseInt(String.valueOf(enterprise.get(0).get("area_code")));
                String enterpriseName = String.valueOf(enterprise.get(0).get("enterprise"));//企业名称
                String areaCodeName = tRegionMapper.selectAreaCode(areaCode);//所属地区
                String industryId = industry;
                String IndustryName = disDictionaryMapper.selectByItemValue(industryId);//所属行业
                jsonObject.put("enterpriseName", enterpriseName);
                jsonObject.put("areaCodeName", areaCodeName);
                jsonObject.put("industryName", IndustryName);
            }

        }
        return json;
    }



    @ApiOperation(value = "业户报警统计下的报警详情")
    @RequestMapping(value = "/enterpriseDetails",method = RequestMethod.GET)
    public JSONObject enterpriseDetails(Integer eId,String date,String limit,String page){
        Map map=new HashMap();
        map.put("eId",String.valueOf(eId));//必传 业户id
        map.put("date",date);//必传 查询日期,yyyy-MM-dd
        map.put("limit",limit);//页面记录数，默认值10
        map.put("page",page);//页码，默认值1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/alarmType/enterpriseDetails";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject jsonObject= JSONObject.parseObject(result);
        JSONObject jo=jsonObject.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return jsonObject;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(json.getString("vId"));//企业id
            List<Map<String,Object>>enterprise=tDisVehicleMapper.selectDetail(vId);
            if (enterprise.size()==0){
                json.put("vehicleNumber",null);
            }else {
                json.put("vehicleNumber", enterprise.get(0).get("vehicleNumber"));
            }
        }
        return jsonObject;
    }




    @ApiOperation(value = "行业报警统计")
    @RequestMapping(value = "/IndustryAlarmStatistics",method = RequestMethod.GET)
    public JSONObject IndustryAlarmStatistics(String startDate,String endDate,Integer industryId,String limit,String page,String regionCode) throws JSONException {
        Map map=new HashMap();
        map.put("startDate",startDate);//必传 查询时间yyyy-MM-dd
        map.put("endDate",endDate);//必传 结束时间yyyy-MM-dd
        map.put("industryId",String.valueOf(industryId));//行业id
        map.put("limit",limit);//必传 页面记录数,默认值为10
        map.put("page",page);//必传 页码，默认值为1
        map.put("regionCode",regionCode);//必传 用户行政区划编码
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/alarmType/industry";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String industry=jsonObject.getString("industryId");//行业id
            String industryTypeId=industry;
            String industryName=disDictionaryMapper.selectIndustryId(industryTypeId);
            jsonObject.put("industryName",industryName);
        }
        return json;
    }



    @ApiOperation(value = "地区报警统计")
    @RequestMapping(value = "/AreaAlarmStatistics",method = RequestMethod.GET)
    public JSONObject AreaAlarmStatistics(String startDate,String endDate,String regionCode,String limit,String page) {
        Map map=new HashMap();
        map.put("startDate",startDate);//必传 查询时间yyyy-MM-dd
        map.put("endDate",endDate);//必传 结束时间yyyy-MM-dd
        map.put("admdivcode",regionCode);//必传 所属区划
        map.put("limit",limit);//页面记录数,默认值为10
        map.put("page",page);//页码，默认值为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/alarmType/region";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer admdivCode=Integer.parseInt(jsonObject.getString("admdivcode"));//地区名
            String areaCodeName=tRegionMapper.selectAreaCode(admdivCode);
            jsonObject.put("areaCodeName",areaCodeName);
        }
        return json;
    }


    @ApiOperation(value = "禁入报警详情")
    @RequestMapping(value = "/inAreaByVidAndDate",method = RequestMethod.GET)
    public JSONObject inAreaByVidAndDate(String vId,String date,String limit,String page){
         Map map=new HashMap();
         map.put("vId",vId);//必传 车辆id
         map.put("data",date);//必传 查询日期yyyy-MMD-dd
         map.put("limit",limit);//页面记录数，默认值为10
         map.put("page",page);//页码，默认值为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistics/inoutAreaRoutine/inAreaByVidAndDate";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject;
    }


    @ApiOperation(value = "禁出报警详情")
    @RequestMapping(value = "/outAreaByVidAndDate",method = RequestMethod.GET)
    public JSONObject OutAreaByVidAndDate(String vId,String date,String limit,String page){
        Map map=new HashMap();
        map.put("vId",vId);//必传 车辆id
        map.put("data",date);//必传 查询日期yyyy-MMD-dd
        map.put("limit",limit);//页面记录数，默认值为10
        map.put("page",page);//页码，默认值为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistics/inoutAreaRoutine/outAreaByVidAndDate";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject;
    }


    @ApiOperation(value = "偏航报警详情")
    @RequestMapping(value = "/yawByVidAndDate",method = RequestMethod.GET)
    public JSONObject yawByVidAndDate(String vId,String date,String limit,String page){
        Map map=new HashMap();
        map.put("vId",vId);//必传 车辆id
        map.put("data",date);//必传 查询日期yyyy-MMD-dd
        map.put("limit",limit);//页面记录数，默认值为10
        map.put("page",page);//页码，默认值为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistics/inoutAreaRoutine/yawByVidAndDate";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject;
    }






    @ApiOperation(value = "车辆轨迹漂移次数统计")
    @RequestMapping(value = "/StatisticsOfVehicleTrajectoryDriftTimes",method = RequestMethod.GET)
    public JSONObject StatisticsOfVehicleTrajectoryDriftTimes(String startTime,String endTime,String limit,String page,String regionCode,String eid,String pName,String vNumber){
        if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        }
        String vIdlist="";
        String pIdList="";
        String vIds=null;
        String pIds=null;
        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber.toUpperCase());
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (pName!=null&& pName.equals("")==false){
            List<Map> pIdsList=tDisPlatformMapper.selectPlatformIdsList(pName);
            if (pIdsList.size()>0){
                for (int i = 0; i < pIdsList.size(); i++) {
                    pIdList=pIdList+pIdsList.get(i).get("platform_id")+",";
                }
                pIds=StringUtils.join(pIdList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        map.put("startTime",startTime);//必选 开始查询时间yyyy-MM-dd HH:mm:ss
        map.put("endTime",endTime);//必选 结束查询时间yyyy-MM-dd HH:mm:ss,查询时间不要超过30天
        map.put("pIds",pIds);//平台id,多个id英文逗号分隔
        map.put("regionCode",regionCode);
        map.put("eIds",eid);//企业id,多个id英文逗号分隔
        map.put("vIds",vIds);//车辆id,多个id英文逗号分隔
        map.put("limit",limit);//页面记录数，默认值为10
        map.put("page",page);//页码，默认为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/vehicleDrift/info";
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            Integer eIds=Integer.parseInt(jsonObject.getString("eId"));//企业id
            String lng=jsonObject.getString("lng");//经度
            String lat=jsonObject.getString("lat");//纬度
            String driftingLocalhost=null;
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eIds);
            String platformName=tDisPlatformMapper.selectpId(pId);
            List<Map<String,Object>>vehicleList=tDisVehicleMapper.selectPNameAndEname(vId);
            if (vehicleList.size()>0){
                jsonObject.put("enterpriseName",vehicleList.get(0).get("enterpriseName"));
                jsonObject.put("platformName",vehicleList.get(0).get("platformName"));
                jsonObject.put("vehicleName",vehicleList.get(0).get("vehicleNumber"));
            }else {
                jsonObject.put("enterpriseName",null);
                jsonObject.put("platformName",null);
                jsonObject.put("vehicleName",null);
            }
            jsonObject.put("driftingLocalhost",driftingLocalhost);
        }
        return json;
    }



    @ApiOperation(value = "车辆入网统计")
    @RequestMapping(value = "/AccessStatistics",method = RequestMethod.POST)
    public LayuiTablePagingResult AccessStatistics(Integer oid,Integer netstatus,String startTime,String endTime,Integer size,Integer page,Integer eid,String pName,String vNumber,Integer level) {
        LayuiTablePagingResult result=null;
        try {

            Integer regionCode=null;
            if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
                result = new LayuiTablePagingResult();
                result.setCode("1009");
                result.setMsg("请输入车牌号不少于3位");
                return result;
            }
            if (level==1){
                regionCode= Integer.valueOf(String.valueOf(oid).substring(0,2));
            }else if (level==2){
                regionCode= Integer.valueOf(String.valueOf(oid).substring(0,4));
            }else if (level==3){
                regionCode= oid;
            }
            List<Map> eIdsLists=new ArrayList<>();
            List<Map> pIdsList=new ArrayList<>();
            if (pName!=null && pName.equals("")==false){
                pIdsList=tDisPlatformMapper.selectPlatformIdsList(pName);
                if (pIdsList.size()==0){
                    result.setCode(RetCode.SUCCESS.getCode());
                    result.setMsg(RetCode.SUCCESS.getMsg());
                    result.setCount((long) 0);
                    result.setData(0);
                    Long totalPages = Long.valueOf(0);
                    result.setTotalPages(totalPages);
                    return result;
                }
            }
            Integer pageNum=(page-1)*size;
            List<Map<String,Object>>vehicleNet=new LinkedList<>();
                if (vNumber!=null){
                    vNumber=vNumber.toUpperCase();
                }
                if (pIdsList.size()>0){
                    for (int j = 0; j < pIdsList.size(); j++) {
                        Map pIdMap=pIdsList.get(j);
                        vehicleNet=tDisEnterpriseMapper.selectVehicleNet(regionCode,netstatus,startTime,endTime,eid,Integer.parseInt(String.valueOf(pIdMap.get("platform_id"))),vNumber,pageNum,size);
                    }
                }else {
                    vehicleNet=tDisEnterpriseMapper.selectVehicleNetAll(regionCode,netstatus,startTime,endTime,eid,null,vNumber,pageNum,size);
                }

            Integer sum;
            if (vehicleNet.get(0).get("total")!=null){
                 sum= Integer.valueOf(String.valueOf(vehicleNet.get(0).get("total")));
            }else {
                sum=0;
            }

            result = new LayuiTablePagingResult();
            result.setCode(RetCode.SUCCESS.getCode());
            result.setMsg(RetCode.SUCCESS.getMsg());
            result.setCount(Long.valueOf(sum));
            result.setData(vehicleNet);
            int totalPages = sum / size;
            if (sum % size != 0){
                totalPages ++;
            }
            result.setTotalPages(Long.valueOf(totalPages));
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

}
